import { useUserStore } from '@/stores';
import router from '@/router';
import axios, { type Method } from 'axios';
import { message } from 'ant-design-vue';

const instance = axios.create({
  baseURL:
    process.env.NODE_ENV === 'development'
      ? import.meta.env.VITE_APP_DEV_BASEURL
      : import.meta.env.VITE_APP_PRO_BASEURL,
  timeout: 10000,
});

instance.interceptors.request.use(
  (config: any) => {
    const store = useUserStore();
    if (store.user?.token && config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user?.token}`;
    }
    return config;
  },
  err => Promise.reject(err)
);

instance.interceptors.response.use(
  res => {
    // 响应码不是201请求失败
    if (res.data?.code !== 201) {
      message.error(res.data?.message);
      return Promise.reject(res.data);
    }
    return res.data;
  },
  err => {
    if (err.response.status === 401) {
      console.log('request', err);
      // 401token失效 不给再鉴权后请求 清空用户信息
      const store = useUserStore();
      store.delUser();
      // 跳转登陆，带上接口失效所在页面的地址，登录完后回跳使用
      router.push(`/login?returnUrl=${router.currentRoute.value.fullPath}`);
    } else if (err.response.status === 400) {
      // message.error(err.response.data?.message.split("constraint:")[1])
      message.error(err.response.data?.message);
      return Promise.reject(err.response.data);
    } else {
      message.error('服务器忙！');
      return Promise.reject(err.response.data?.message);
    }
    return Promise.reject(err);
  }
);

type Data<T> = {
  code: number;
  success: Boolean;
  message: string;
  data: T;
};

// 导出一个通用的请求工具函数
const request = <T>(url: string, method: Method = 'get', submiData?: object) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submiData,
  });
};

export { instance, request };
